package com.gitee.minimalismstyle.fresh.common.data.redis

import com.gitee.minimalismstyle.fresh.common.core.extra.log
import org.redisson.api.RedissonClient
import org.springframework.stereotype.Component
import java.util.concurrent.TimeUnit

@Component
class RedisUtils(val redissonClient: RedissonClient) {

    fun lock(key: String, predicate: () -> Unit){
        lock(key, 30000){
            predicate()
        }
    }

    fun lock(key: String, timeout: Long, predicate: () -> Unit){
        val rlock = redissonClient.getLock(key)
        try {
            rlock.lock(timeout, TimeUnit.MILLISECONDS)
            log.debug("已锁定【key=${key}】")
            predicate()
        } catch (throwable: Throwable) {
            throw throwable
        }finally {
            rlock.unlock()
            log.debug("已解锁【key=${key}】")
        }
    }
}
